package com.saas.service.weixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.saas.service.APIService;
import com.saas.util.APPUtils;
import com.saas.util.HttpClientUtil;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Component
public class WeixinService {
	private Logger logger = Logger.getLogger(getClass());
	
	private static JSONObject weixinAccessToken=null;
	private static JSONObject weixinTicket=null;
	
	private static final String APP_ID = "wx596816a493629095";
	private static final String APP_SECRET = "60f8a20e134a77f6b5a4f8f12fa2e99e";

	@Autowired
	private APIService apiService;
	
//	@Autowired
//	private CacheService cacheService;
	
	//获取weixin openid
	public String getOpenId(String code) throws Exception{
		// 先获取ACCESS_TOKEN
		String openId = "";

		String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APP_ID+"&secret="+APP_SECRET+"&code="+code+"&grant_type=authorization_code";
		HttpMethod method = new GetMethod(token_url);
		String res = HttpClientUtil.httpRequest(method);
		if (!"none".equals(res)) {
			/* {"access_token":"ACCESS_TOKEN","expires_in":7200} */
			JSONObject jsonobj =JSON.parseObject(res);
			jsonobj.put("timestamp", System.currentTimeMillis());
			openId = jsonobj.getString("openid");
			logger.info("获取微信openid成功：" + openId);
		} else {
			logger.info("获取微信openid失败");
			throw new Exception("获取微信openid失败");
		}
		return openId;
	}
	
	private synchronized String getWeixinAccessToken() throws Exception {
		if(weixinAccessToken!=null){
			long timeStamp=weixinAccessToken.getLong("timestamp");
			if(System.currentTimeMillis()-timeStamp<700*1000){
				return weixinAccessToken.getString("access_token");
			}
		}
		// 先获取ACCESS_TOKEN
		String ACCESS_TOKEN = "";

		String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"
				+ "&appid=" + APP_ID + "&secret=" + APP_SECRET;
		HttpMethod method = new GetMethod(token_url);
		String res = HttpClientUtil.httpRequest(method);
		if (!"none".equals(res)) {
			/* {"access_token":"ACCESS_TOKEN","expires_in":7200} */
			JSONObject jsonobj =JSON.parseObject(res);
			jsonobj.put("timestamp", System.currentTimeMillis());
			weixinAccessToken=jsonobj;
			ACCESS_TOKEN = jsonobj.getString("access_token");
			logger.info("获取微信ACCESS_TOKEN成功：" + ACCESS_TOKEN);
		} else {
			logger.info("获取微信ACCESS_TOKEN失败");
			throw new Exception("获取微信ACCESS_TOKEN失败");
		}
		return ACCESS_TOKEN;
	}

	public String getWeixinTicket(String token) throws Exception{
		if(weixinTicket!=null){
			long timeStamp=weixinTicket.getLong("timestamp");
			if(System.currentTimeMillis()-timeStamp<7000*1000){
				return weixinTicket.getString("ticket");
			}
		}
		// 获取jsapi_ticket
		String sign_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="
				+ token + "&type=jsapi";
		String jsapi_ticket = "";
		HttpMethod method = new GetMethod(sign_url);
		logger.info("prepare to request:"+sign_url);
		String res = HttpClientUtil.httpRequest(method);
		if (!"none".equals(res)) {
			/*
			 * { "errcode":0, "errmsg":"ok", "ticket":"bxwJ0m9E8",
			 * "expires_in":7200 }
			 */
			JSONObject jsonobj = JSON.parseObject(res);
			int errcode = jsonobj.getIntValue("errcode");
			if (errcode == 0) {
				jsapi_ticket = jsonobj.getString("ticket");
				logger.info("获取微信jsapi_ticket成功：" + jsapi_ticket);
				jsonobj.put("timestamp", System.currentTimeMillis());
				weixinTicket=jsonobj;
			} else {
				logger.info("获取微信jsapi_ticket失败");
				weixinAccessToken=null;
				throw new Exception("获取微信jsapi_ticket失败");
			}
		} else {
			logger.info("获取微信jsapi_ticket失败");
			throw new Exception("获取微信jsapi_ticket失败");
		}
		return jsapi_ticket;
	}
	public void resetSign(){
		WeixinService.weixinAccessToken=null;
		WeixinService.weixinTicket=null;
	}
	

	public JSONObject getUserDetails(String accessToken,String openId,String code) throws Exception {
		//先获取ACCESS_TOKEN
		String token_url = "https://api.weixin.qq.com/sns/userinfo"
						+ "?access_token="+accessToken
						+ "&openid="+openId
						+ "&lang=zh_CN";
				HttpMethod method = new GetMethod(token_url);
				String res = HttpClientUtil.httpRequest(method);
				if(!"none".equals(res)){
					/*{
					   "openid":" OPENID",
					   " nickname": NICKNAME,
					   "sex":"1",
					   "province":"PROVINCE"
					   "city":"CITY",
					   "country":"COUNTRY",
					    "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46", 
						"privilege":[
						"PRIVILEGE1"
						"PRIVILEGE2"
					    ]
					    "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
					}*/
					JSONObject jsonobj = JSON.parseObject(res);
					logger.info("获取微信USERINFO成功："+jsonobj.toString());
					return jsonobj;
				}else{
					logger.info("获取微信USERINFO失败");
					throw new Exception("获取微信USERINFO失败");
				}
	}
	
	/**
	 * 获取weixin公众号的access_token
	 * @return
	 * @throws Exception
	 */
	public String getAccessToken() throws Exception {
//		String accessTokenCacheKey = "weixin_accessToken_key";
//		String accessToken = cacheService.get(accessTokenCacheKey);
//		if(StringUtils.isBlank(accessToken)){
//			accessToken = this.getWeixinAccessToken();
//			if(StringUtils.isBlank(accessToken)) throw new Exception("获取weixin access_token失败");
//			//设置7000s过期，比微信过期时间短200秒，防止redis过期不及时导致的access_token无效
//			cacheService.setex(accessTokenCacheKey, 7000, accessToken);
//		}
//		return accessToken;

		return null;
	}
	
	private RestTemplate restTemplate=new RestTemplate();
	
	/**
	 * @param query { 
				"begin_date": "2014-12-02", 
    			"end_date": "2014-12-07"
				}
	 * @return
	 * @throws Exception
	 */
	public JSONObject getUserSummary(JSONObject query) throws Exception {
		/**
		 * https://api.weixin.qq.com/datacube/getusersummary?access_token=ACCESS_TOKEN
		 */
		String host = "https://api.weixin.qq.com/datacube/getusersummary?access_token="+this.getAccessToken();
		MultiValueMap<String, String> map1 = new LinkedMultiValueMap<String, String>();
		map1.set("content-type", "text/json;charset=UTF-8");
		map1.set(APPUtils.Authorization, APPUtils.base64Encoder(APPUtils.public_authData, APPUtils.CHARSET));
		HttpEntity<String> httpEntity2 = new HttpEntity<String>(query.toJSONString(), map1);
		ResponseEntity<JSONObject> res = restTemplate.postForEntity(host, httpEntity2, JSONObject.class);
		return res.getBody();
	}
	
	/**
	 * @param query { 
				"begin_date": "2014-12-02", 
    			"end_date": "2014-12-07"
				}
	 * @return
	 * @throws Exception
	 */
	public JSONObject getUserCumulate(JSONObject query) throws Exception {
		/**
		 * https://api.weixin.qq.com/datacube/getusersummary?access_token=ACCESS_TOKEN
		 */
		String host = "https://api.weixin.qq.com/datacube/getusercumulate?access_token="+this.getAccessToken();
		MultiValueMap<String, String> map1 = new LinkedMultiValueMap<String, String>();
		map1.set("content-type", "text/json;charset=UTF-8");
		map1.set(APPUtils.Authorization, APPUtils.base64Encoder(APPUtils.public_authData, APPUtils.CHARSET));
		HttpEntity<String> httpEntity2 = new HttpEntity<String>(query.toJSONString(), map1);
		ResponseEntity<JSONObject> res = restTemplate.postForEntity(host, httpEntity2, JSONObject.class);
		return res.getBody();
	}
}

